package bibbletex.helpers;

import java.io.DataInputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import bibbletex.models.Collaboration;
import bibbletex.models.Reference;

public class FileHelper {

	public static void writeFile(Collaboration c, HttpServletResponse response) {
		response.reset();
		response.setContentType("application/text");
		response.setHeader("Content-disposition",
				"attachment; filename=bibliography.bib");

		try {
			for (Reference r : c.getReferences())
				response.getWriter().print(BibtexFormat.toString(r));

			response.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String readFile(DataInputStream in, int length,
			String contenttype) {
		byte dataBytes[] = new byte[length];
		int byteRead = 0;
		int totalBytesRead = 0;
		try {
			while (totalBytesRead < length) {
				byteRead = in.read(dataBytes, totalBytesRead, length);
				totalBytesRead += byteRead;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		String file = new String(dataBytes, 0, totalBytesRead);
		int lastindex = contenttype.lastIndexOf("=");
		String boundary = contenttype.substring(lastindex + 1,
				contenttype.length());
		int position;
		position = file.indexOf("filename=\"");
		position = file.indexOf("\n", position) + 1;
		position = file.indexOf("\n", position) + 1;
		position = file.indexOf("\n", position) + 1;
		int boundaryLocation = file.indexOf(boundary, position) - 4;
		int startposition = ((file.substring(0, position)).getBytes()).length;
		int endposition = ((file.substring(0, boundaryLocation)).getBytes()).length;
		
		return new String(dataBytes, startposition, (endposition - startposition));
	}
}
